package com.qf.service.Impl;

import com.qf.mapper.UserMapper;
import com.qf.model.User;
import com.qf.page.PageResult;
import com.qf.page.QueryPageBean;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public List<User> GetAll() {
        List<User> list = userMapper.selectAll();
        return list;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageResult pageResult = new PageResult();
        Integer currentPage = queryPageBean.getCurrentPage(); //当前页
        Integer pageSize = queryPageBean.getPageSize();//每页大小
        //total 总记录数
        List<User> page = userMapper.findPage((currentPage - 1) * pageSize, pageSize);
        //rows  当前页的数据
        Long count = userMapper.count();
        pageResult.setRows(page);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    @Transactional
    public int addUser(User user) {
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        user.setUpdatetime(new Date());
        int row = userMapper.insertUser(user);
        return row;
    }

    @Override
    public User findById(int id) {
        User user =new User();
        user.setUpdatetime(new Date());
        User u = userMapper.findById(id);
        return u;
    }

    @Override
    @Transactional
    public int edit(User user) {
        user.setUpdatetime(new Date());
        int row = userMapper.update(user);
        return row;
    }

    @Override
    @Transactional
    public int deleteById(Integer id) {
        int row = userMapper.delById(id);
        return row;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //校验用户名
        User user = userMapper.findByUsername(username);
        if (user ==null){
            System.out.println("密码或者用户名错误");
            return null;
        }
        //授权
        List<GrantedAuthority> list = new ArrayList<>();//权限的集合
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }

}
